-- 工具文件
-- 2021.05.08
-- Lingd
-- 福州泰诚网络科技有限公司

module(...,package.seeall)

-- ASCII转HEX字符串，并根据指定字符进行分隔
function AsciitoHexStr(str,char)
    local i,hexstr = 1,""
    for i = 1,string.len(str) do
        hexstr = hexstr .. string.sub(str,i,i):toHex()
        if i < string.len(str) then
            hexstr = hexstr .. char
        end
    end 
    return hexstr
end

-- HEX转HEX字符串，并根据指定字符进行分隔
function HextoHexStr(hex,char)
    local i,hexstr = 1,""
    for i = 1,#hex do
        hexstr = hexstr .. string.format("%02X",hex[i])
        if i < #hex then
            hexstr = hexstr .. char
        end
    end 
    return hexstr
end

-- HEX字符串分割
function Split(str,pattern)
    local i,ret = 1,{}
    for item in string.gmatch( str, "(.-)"..pattern) do
        ret[i] = item
        i = i + 1
    end
    return ret
end

-- HEX字符串转数组
function HexStrToTable(str)
    local i,buf = 1,{}
    -- “123456”字符串分解为‘1’‘2’‘3’‘4’‘5’‘6’
    for i = 1,string.len(str) do
        buf[i] = string.byte(string.sub(str,i,i))
    end    
    
    return buf
end

-- NumBer数组转NumBer
function TableToNumber(tab,sta,len)
    local i, str = 1, ""
	
	if i+sta+len > #tab then return -1 end
	
	for i = 1,len do
		str = str .. string.char(tab[i+sta])
	end
	
    return tonumber(str)
end

-- NumBer数组转String
function TableToString(tab,sta,len)
    local i, str = 1, ""
	
	if sta+len > #tab then return -1 end
	
	for i = 1,len do
		str = str .. string.char(tab[i+sta])
	end
	
    return str
end

-- 日期字符串转时间戳
function DateStrToSec(str)
	
	local statime = os.time({
		year 	= tonumber(string.sub(str,1,2))+2000,
		month 	= tonumber(string.sub(str,3,4)),
		day 	= tonumber(string.sub(str,5,6)),
		hour 	= tonumber(string.sub(str,7,8)),
		minute 	= 0,
		second 	= 0
	})
	
	return statime+tonumber(string.sub(str,9,10))*60+tonumber(string.sub(str,11,12))
end

-- NumBer保留N位小数
function GetPreciseDecimal(num, n)
    local ret = string.format("%5."..n.."f",num)
    return tonumber(ret)
end